<?php
declare (strict_types = 1);

namespace app\controller\backend\maintain;

use app\controller\backend\BackendController;
use app\service\logic\common\maintain\InfoService;
use app\validate\common\maintain\InfoValidate;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;
use think\response\Json;

class InfoController extends BackendController
{
    protected $service;

    public function __construct(App $app, InfoService $service)
    {
        parent::__construct($app);

        $this->service = $service;
    }

    /**
     * 视图
     *
     * @return string
     */
    public function view(): string
    {
        return $this->layout('backend/maintain/info', 'maintain_info');
    }

    /**
     * 下拉菜单
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function options(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);
        $search['company_id'] = $this->request->middleware('company')['company_id'];

        $drop = $this->service->getOptions($params, $search_fields, $search);
        return amis(['options' => $drop]);
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $params = $request->only($this->service->getSaveColumn());
        $params['admin_id'] = $request->middleware('admin')['id'];
        $this->validate($params, InfoValidate::class . '.save');

        $result = $this->service->create($params);

        return amis($result);
    }

    /**
     * 显示资源
     *
     * @param Request $request
     * @return Json
     */
    public function read(Request $request): Json
    {
        $params = $request->only(['type']);
        $result = $this->service->getSimpleDetail($params);
        return amis($result);
    }
}
